<template>
  <el-dialog
  title="编辑用户"
  :visible.sync="formVisible"
  width="500px">
  <el-form
  :model="editForm"
  size="mini"
  ref="FormEl"
  :rules="formRules">
    <el-form-item label="用户名" label-width="80px" prop="username">
      <el-input v-model="editForm.username" autocomplete="off" disabled></el-input>
    </el-form-item>
    <el-form-item label="邮箱" label-width="80px" prop="email">
      <el-input v-model="editForm.email" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="手机" label-width="80px" prop="mobile">
      <el-input v-model="editForm.mobile" autocomplete="off"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="formVisible = false">取 消</el-button>
    <el-button type="primary" @click.prevent="handleEdit">确 定</el-button>
  </div>
</el-dialog>
</template>

<script>
import { getById as getUserById, updateById as updateUserById } from '@/api/user'

export default {
  name: 'UserEdit',
  data () {
    return {
      formVisible: false,
      editForm: {
        username: '',
        email: '',
        mobile: ''
      },
      formRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleEdit () {
      this.$refs.FormEl.validate(valid => {
        if (!valid) {
          return
        }
        this.submitEdit()
      })
    },
    async submitEdit () {
      const { id, email, mobile } = this.editForm
      const { meta } = await updateUserById(id, {
        email,
        mobile
      })
      if (meta.status === 200) {
        // 更新列表数据
        // 编辑成功，发布一个自定义事情
        // 这个事件就表示：编辑成功
        this.$emit('edit-success')
        this.$message({
          type: 'success',
          message: '更新成功'
        })
        // 隐藏对话框
        this.formVisible = false
      }
    },
    async showEditDialog (item) {
      const { data, meta } = await getUserById(item.id)
      if (meta.status === 200) {
        this.editForm = data
        this.formVisible = true // 显示弹框
      }
    }
  }
}
</script>

<style>

</style>
